<?php

namespace app\controllers\api;

use app\models\News;
use app\models\Transfer;
use app\models\User;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class TransferController extends BaseController {
    public function actionTransfer() {
        $user = $this->check();
        $this->checkModify();
        $post = Yii::$app->request->post();
        $model = new Transfer();
        $model->loadBeforeFilter($post, ['income_user_id', 'num', 'reason', ]);
        $model->transfer_user_id = $user->id;
        if(!$model->income_user_id) {
            throw new UserException('转账人未选择');
        }
        if(!($model->num > 0)) {
            throw new UserException('转账金额错误');
        }
        if(!$model->reason) {
            throw new UserException('转账原因未填写');
        }
        $model->transfer_time = date('Y-m-d H:i:s');
        $this->transaction(function() use($model) {
            $model->save();

            $this->logForUser($model->transferUser, '转账 - 转出', $model->id, -$model->num);
            $this->logForUser($model->incomeUser, '转账 - 收到', $model->id, $model->num);
            $this->message($model->incomeUser, '收到转账', '/transfer/index', 'fa fa-credit-card-alt text-yellow');
        });
        return $this->renderSuccess([]);
    }

    public function actionList() {
        $user = $this->check();
        $models = Transfer::find()
            ->andWhere(['or', ['income_user_id'=>$user->id], ['transfer_user_id'=>$user->id]])
            ->all();
        $this->log('转账 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }
}
